<template>
  <div>
    <el-row style="margin-bottom: 10px">
      <el-row>
        <el-button size="small" type="success" @click="handleAdd">新增</el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleAllDelete"
          :disabled="!multipleForms.length"
          >全部删除</el-button
        >
      </el-row>
      <!-- <el-row>
        <el-button size="small" type="success">保存</el-button>
      </el-row> -->
    </el-row>
    <!-- 遍历出来的表格 -->
    <el-scrollbar :height="height" ref="scrollbarRef" v-loading="loading">
      <div v-for="item in multipleForms" class="mutipleFormsClass">
        <el-form :model="item" label-width="100">
          <el-form-item label="当前模板字段：" prop="targetComponentName">
            {{ item.targetComponentName }}
          </el-form-item>
          <el-form-item label="引用模板：" prop="sourceTableName">
            {{ item.sourceTableName }}
          </el-form-item>
          <el-form-item label="引用字段：" prop="sourceComponentName">
            {{ item.sourceComponentName }}
          </el-form-item>
        </el-form>
        <p class="pinformation" v-show="item.ruleType == 1">引用规则</p>
        <el-table :data="item.ruleList" style="margin-bottom: 5px" max-height="20vh" v-show="item.ruleType == 1">
          <el-table-column
            label="当前表控件"
            align="center"
            prop="targetRuleComponentName"
          />
          <el-table-column
            label="引用表控件"
            align="center"
            prop="sourceRuleComponentName"
          />
        </el-table>
        <el-row justify="end" style="margin-bottom: 10px">
          <el-button type="success" @click="handleCopy(item)">复制</el-button>
          <el-button type="success" @click="handleEdit(item)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(item)">删除</el-button>
        </el-row>
      </div>
      <div style="height: 20px"></div>
    </el-scrollbar>
    <el-dialog
      :class="'el-dialog-theme3'"
      v-model="importRuleOpen"
      :title="importRuleTitle"
      @close="closedDialog"
      draggable
      :close-on-click-modal="false"
      width="650"
    >
      <el-form :model="importRuleForm" ref="dialogRef" label-width="110" :rules="rules">
        <el-form-item label="当前模板字段：" prop="targetComponentId">
          <el-select
            v-model="importRuleForm.targetComponentId"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in componentList"
              :key="item.componentId"
              :value="item.componentId"
              :label="item.componentName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="引用模板：" prop="sourceTableId">
          <el-select
            v-model="importRuleForm.sourceTableId"
            filterable
            clearable
            remote
            :remote-method="remoteMethod"
            :loading="loading1"
            remote-show-suffix
            @change="childChange(importRuleForm.sourceTableId, false)"
            style="width: 100%"
          >
            <el-option
              v-for="item in childTableList"
              :key="item.tableId"
              :value="item.tableId"
              :label="item.tableName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="引用字段：" prop="sourceComponentId">
          <el-select
            v-model="importRuleForm.sourceComponentId"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in mainComponentList"
              :key="item.componentId"
              :value="item.componentId"
              :label="item.componentName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测类别：" prop="jclbIds">
          <el-select
            v-model="importRuleForm.jclbIds"
            clearable
            filterable
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="4"
            style="width: 100%"
          >
            <el-option
              v-for="item in jclbList"
              :key="item.jclbId"
              :value="item.jclbId"
              :label="item.jclbName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="引用规则：" prop="ruleType">
          <el-radio-group v-model="importRuleForm.ruleType" @change="ruleTypeChange">
            <el-radio :label="0">自动匹配</el-radio>
            <el-radio :label="1">手动匹配</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-row v-show="importRuleForm.ruleType == 1">
        <p class="pinformation">引用规则</p>
        <p class="totalStyle">共 {{ importRuleForm.ruleList?.length }} 条数据</p>
        <el-row style="margin-bottom: 5px">
          <el-button
            type="success"
            link
            @click="handleRuleAdd"
            icon="plus"
            style="margin-left: 15px"
            >新增</el-button
          >
        </el-row>
      </el-row>
      <el-table
        :data="importRuleForm.ruleList"
        max-height="40vh"
        v-show="importRuleForm.ruleType == 1"
        >>
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="当前表控件" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.targetRuleComponentId"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in componentList"
                :key="item.componentId"
                :value="item.componentId"
                :label="item.componentName"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="引用表控件" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.sourceRuleComponentId"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in mainComponentList"
                :key="item.componentId"
                :value="item.componentId"
                :label="item.componentName"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" type="index" width="80">
          <template #default="scope">
            <el-button link icon="Delete" @click="handleRuleDelete(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="save">确定</el-button>
          <el-button type="danger" @click="importRuleOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import bus from "@/utils/eventBus";
import {
  getIsChild,
  getIsMain,
  templateComponentRel,
  getRuleList,
  getRuleListView,
  delRuleList,
  delAllRuleList,
} from "@/api/templateEditor/table";
import { allListJclb } from "@/api/store/jclb";
import { onMounted } from "vue";

const route = useRoute();

const { proxy } = getCurrentInstance();

const multipleForms = ref([]);
const height = ref();
const componentList = ref([]);
const childTableList = ref([]);
const mainComponentList = ref([]);
const importRuleOpen = ref(false);
const loading = ref(false);
const loading1 = ref(false);
const importRuleTitle = ref("");
const importRuleForm = ref({ ruleList: [], ruleType: "0" });
const jclbList = ref([]);
const rules = ref({
  targetComponentId: [
    { required: true, message: "当前模板字段不能为空", trigger: "blur" },
  ],
  sourceTableId: [{ required: true, message: "引用模板不能为空", trigger: "blur" }],
  sourceComponentId: [{ required: true, message: "引用字段不能为空", trigger: "blur" }],
});

function getList() {
  loading.value = true;
  getRuleList({ targetTableId: route.query.tableId }).then((res) => {
    multipleForms.value = res.data;
    loading.value = false;
  });
}

function handleAdd() {
  importRuleOpen.value = true;
  importRuleTitle.value = "新增引用规则";
  allListJclb().then((res) => {
    jclbList.value = res.data;
  });
  importRuleForm.value.ruleType = 0;
}

function handleEdit(row) {
  return new Promise((resolve, reject) => {
    importRuleOpen.value = true;
    allListJclb().then((res) => {
      jclbList.value = res.data;
    });
    getRuleListView(row.relId).then((res) => {
      importRuleForm.value = res.data;
      childTableList.value = [
        {
          tableId: importRuleForm.value.sourceTableId,
          tableName: importRuleForm.value.sourceTableName,
        },
      ];
      childChange(importRuleForm.value.sourceTableId, true);
      resolve();
    });
  });
}

function handleCopy(row) {
  handleEdit(row).then(() => {
    delete importRuleForm.value.relId;
    importRuleForm.value.ruleList.forEach((item) => {
      delete item.ruleId;
    });
  });
}

function handleRuleAdd() {
  if(!importRuleForm.value.ruleList){
  importRuleForm.value.ruleList = [];
}
importRuleForm.value.ruleList.push({});
}

function ruleTypeChange(value) {}

function handleRuleDelete(row) {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      importRuleForm.value.ruleList.splice(row, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleDelete(row) {
  proxy.$modal.confirm("确认要删除此引用规则吗？").then(function () {
    delRuleList(row.relId).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
  });
}

function handleAllDelete(row) {
  proxy.$modal.confirm("确认要删除全部引用规则吗？").then(function () {
    delAllRuleList(route.query.tableId).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
  });
}

function remoteMethod(val) {
  if (!val) {
    childTableList.value = [];
    return false;
  }
  loading1.value = true;
  getIsChild({ tableCondition: val }).then((res) => {
    childTableList.value = res.rows;
    loading1.value = false;
  });
}

function childChange(val, bs) {
  mainComponentList.value = [];
  if (!bs) {
    delete importRuleForm.value.sourceComponentId;
    importRuleForm.value.ruleList.forEach((item) => {
      delete item.sourceRuleComponentId;
    });
  }
  if (!val) return;
  getIsMain(val).then((res) => {
    mainComponentList.value = res.data;
  });
}

function save() {
  proxy.$refs["dialogRef"].validate((valid) => {
    if (valid) {
      if (importRuleForm.value.ruleType == 1) {
        if (!importRuleForm.value.ruleList || importRuleForm.value.ruleList.length == 0) {
          proxy.$modal.msgError("至少有一条引用规则");
          return;
        }
        let isto = true;
        for (const item of importRuleForm.value.ruleList) {
          if (!item.targetRuleComponentId || !item.sourceRuleComponentId) {
            isto = false;
            break;
          }
        }
        if (!isto) {
          proxy.$modal.msgError("请将引用规则补充完整");
          return;
        }
      }
      importRuleForm.value.targetTableId = route.query.tableId;
      delete importRuleForm.value.sourceTableName;
      templateComponentRel(importRuleForm.value).then((res) => {
        proxy.$modal.msgSuccess("保存成功");
        importRuleOpen.value = false;
        getList();
      });
    }
  });
}

function closedDialog() {
  importRuleForm.value = { ruleList: [] };
  if (proxy.$refs["dialogRef"]) {
    proxy.$refs["dialogRef"].clearValidate();
  }
}

bus.on("tempComponent", (val) => {
  componentList.value = val.filter((item) => {
    return item.isHide == 0;
  });
});

function getHeight() {
  nextTick(() => {
    height.value = proxy.getSubFileHeight(proxy, "scrollbarRef");
  });
}

onMounted(() => {
  getList();
});

function getMountedHeight() {
  nextTick(() => {
    getHeight();
    window.addEventListener("resize", getHeight);
  });
}

function getUnmountHeight() {
  window.removeEventListener("resize", getHeight);
}

defineExpose({
  getMountedHeight,
  getUnmountHeight,
});
</script>

<style lang="scss">
.mutipleFormsClass {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid;
  border-radius: 15px;
}
</style>
